{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h1 align=\"center\">Image Display</h1>\n",
    "\n",
    "The native SimpleITK approach to displaying images is to use an external viewing program. In the notebook environment it is convenient to use matplotlib to display inline images and if the need arises we can implement some reasonably rich inline graphical user interfaces, combining control components from the ipywidgets package and matplotlib based display.\n",
    "\n",
    "In this notebook we cover the usage of external programs and matplotlib for viewing images. We also instantiate a more involved inline interface that uses ipywidgets to control display. For the latter type of moderately complex display, used in many of the notebooks, take a look at the [gui.py](gui.py) file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import print_function\n",
    "\n",
    "import SimpleITK as sitk\n",
    "\n",
    "%matplotlib notebook\n",
    "import matplotlib.pyplot as plt\n",
    "import gui\n",
    "\n",
    "# Utility method that either downloads data from the Girder repository or\n",
    "# if already downloaded returns the file name for reading from disk (cached data).\n",
    "%run update_path_to_download_script\n",
    "from downloaddata import fetch_data as fdata"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## Image Display with An External Viewer\n",
    "\n",
    "SimpleITK provides two options for invoking an external viewer, use a procedural interface or an object oriented one. \n",
    "\n",
    "### Procedural interface\n",
    "SimpleITK provides a built in ``Show`` method. This function writes the image out to disk and than launches a program for visualization. By default it is configured to use the Fiji program, because it readily supports many medical image formats and loads quickly. However, the ``Show`` visualization program is easily customizable via environment variables:\n",
    "\n",
    "<ul>\n",
    "<li>SITK_SHOW_COMMAND: Viewer to use (<a href=\"http://www.itksnap.org\">ITK-SNAP</a>, <a href=\"http://www.slicer.org\">3D Slicer</a>...) </li>\n",
    "<li>SITK_SHOW_COLOR_COMMAND: Viewer to use when displaying color images.</li>\n",
    "<li>SITK_SHOW_3D_COMMAND: Viewer to use for 3D images.</li>\n",
    "</ul>\n",
    "\n",
    "In general, the Show command accepts three parameters: (1) image to display; (2) window title; (3) boolean specifying whether to print the invoked command and additional debugging information."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mr_image = sitk.ReadImage(fdata('training_001_mr_T1.mha'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sitk.Show?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    sitk.Show(mr_image)\n",
    "except RuntimeError:\n",
    "    print('SimpleITK Show method could not find the viewer (ImageJ not installed or ' +\n",
    "          'environment variable pointing to non existant viewer).')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Use a different viewer by setting environment variable(s). Do this from within your Jupyter notebook using 'magic' functions, or set in a more permanent manner using your OS specific convention. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%env SITK_SHOW_COMMAND /Applications/ITK-SNAP.app/Contents/MacOS/ITK-SNAP \n",
    "\n",
    "try:\n",
    "    sitk.Show(mr_image)\n",
    "except RuntimeError:\n",
    "    print('SimpleITK Show method could not find the viewer (ITK-SNAP not installed or ' +\n",
    "          'environment variable pointing to non existant viewer).')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%env SITK_SHOW_COMMAND '/Applications/ImageJ/ImageJ.app/Contents/MacOS/JavaApplicationStub'\n",
    "try:\n",
    "    sitk.Show(mr_image)\n",
    "except RuntimeError:\n",
    "    print('SimpleITK Show method could not find the viewer (ImageJ not installed or ' +\n",
    "          'environment variable pointing to non existant viewer).')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%env SITK_SHOW_COMMAND '/Applications/Slicer.app/Contents/MacOS/Slicer'\n",
    "try:\n",
    "    sitk.Show(mr_image)\n",
    "except RuntimeError:\n",
    "    print('SimpleITK Show method could not find the viewer (Slicer not installed or ' +\n",
    "          'environment variable pointing to non existant viewer).')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Object Oriented interface\n",
    "\n",
    "The [Image Viewer](https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1ImageViewer.html) class provides a more standard approach to controlling image viewing by setting various instance variable values. Also, it ensures that all of your viewing settings are documented, as they are part of the code and not external environment variables.\n",
    "\n",
    "A caveat to this is that if you have set various environment variables to control SimpleITK settings, the image viewer will use these settings as the default ones and not the standard defaults (Fiji as viewer etc.)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "simpleitk_error_allowed": "Exception thrown in SimpleITK ImageViewer_Execute:"
   },
   "outputs": [],
   "source": [
    "# Which external viewer will the image_viewer use if we don't specify the external viewing application? \n",
    "# (see caveat above)\n",
    "image_viewer = sitk.ImageViewer()\n",
    "image_viewer.SetApplication('/Applications/Fiji.app/Contents/MacOS/ImageJ-macosx')\n",
    "image_viewer.SetTitle('MR image')\n",
    "\n",
    "# Use the default image viewer.\n",
    "image_viewer.Execute(mr_image)\n",
    "\n",
    "# Change viewer, and display again.\n",
    "image_viewer.SetApplication('/Applications/ITK-SNAP.app/Contents/MacOS/ITK-SNAP')\n",
    "image_viewer.Execute(mr_image)\n",
    "\n",
    "# Change the viewer command, (use ITK-SNAP -z option to open the image in zoomed mode)\n",
    "image_viewer.SetCommand('/Applications/ITK-SNAP.app/Contents/MacOS/ITK-SNAP -z 3')\n",
    "image_viewer.Execute(mr_image)\n",
    "\n",
    "print('Default format for saved file used in display: ' + image_viewer.GetFileExtension())\n",
    "\n",
    "# Change the file format (possibly to make it compatible with your viewer of choice)\n",
    "image_viewer.SetFileExtension('.nrrd')\n",
    "image_viewer.Execute(mr_image)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Inline display with matplotlib"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mr_image = sitk.ReadImage(fdata('training_001_mr_T1.mha'))\n",
    "npa = sitk.GetArrayViewFromImage(mr_image)\n",
    "\n",
    "# Display the image slice from the middle of the stack, z axis\n",
    "z = int(mr_image.GetDepth()/2)\n",
    "npa_zslice = sitk.GetArrayViewFromImage(mr_image)[z,:,:]\n",
    "\n",
    "# Three plots displaying the same data, how do we deal with the high dynamic range?\n",
    "fig = plt.figure(figsize=(10,3))\n",
    "\n",
    "fig.add_subplot(1,3,1)\n",
    "plt.imshow(npa_zslice)\n",
    "plt.title('default colormap', fontsize=10)\n",
    "plt.axis('off')\n",
    "\n",
    "fig.add_subplot(1,3,2)\n",
    "plt.imshow(npa_zslice,cmap=plt.cm.Greys_r);\n",
    "plt.title('grey colormap', fontsize=10)\n",
    "plt.axis('off')\n",
    "\n",
    "fig.add_subplot(1,3,3)\n",
    "plt.title('grey colormap,\\n scaling based on volumetric min and max values', fontsize=10)\n",
    "plt.imshow(npa_zslice,cmap=plt.cm.Greys_r, vmin=npa.min(), vmax=npa.max())\n",
    "plt.axis('off');"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Display the image slice in the middle of the stack, x axis\n",
    "    \n",
    "x = int(mr_image.GetWidth()/2)\n",
    "\n",
    "npa_xslice = npa[:,:,x]\n",
    "plt.figure(figsize=(10,2))\n",
    "plt.imshow(npa_xslice, cmap=plt.cm.Greys_r)\n",
    "plt.axis('off')\n",
    "\n",
    "print('Image spacing: {0}'.format(mr_image.GetSpacing()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Collapse along the x axis\n",
    "extractSliceFilter = sitk.ExtractImageFilter()     \n",
    "size = list(mr_image.GetSize())\n",
    "size[0] = 0\n",
    "extractSliceFilter.SetSize( size )\n",
    "         \n",
    "index = (x, 0, 0)\n",
    "extractSliceFilter.SetIndex(index)\n",
    "sitk_xslice = extractSliceFilter.Execute(mr_image)\n",
    "\n",
    "# Resample slice to isotropic\n",
    "original_spacing = sitk_xslice.GetSpacing()\n",
    "original_size = sitk_xslice.GetSize()\n",
    "\n",
    "min_spacing = min(sitk_xslice.GetSpacing())\n",
    "new_spacing = [min_spacing, min_spacing]\n",
    "new_size = [int(round(original_size[0]*(original_spacing[0]/min_spacing))), \n",
    "            int(round(original_size[1]*(original_spacing[1]/min_spacing)))]\n",
    "resampleSliceFilter = sitk.ResampleImageFilter()\n",
    "\n",
    "# Why is the image pixelated?\n",
    "sitk_isotropic_xslice = resampleSliceFilter.Execute(sitk_xslice, new_size, sitk.Transform(), sitk.sitkNearestNeighbor, sitk_xslice.GetOrigin(),\n",
    "                                                    new_spacing, sitk_xslice.GetDirection(), 0, sitk_xslice.GetPixelID())\n",
    "plt.figure(figsize=(10,2))\n",
    "plt.imshow(sitk.GetArrayViewFromImage(sitk_isotropic_xslice), cmap=plt.cm.Greys_r)\n",
    "plt.axis('off')\n",
    "print('Image spacing: {0}'.format(sitk_isotropic_xslice.GetSpacing()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## Inline display with matplotlib and ipywidgets\n",
    "\n",
    "Display two volumes side by side, with sliders to control the displayed slice. The menu on the bottom left allows you to home (return to original view), back and forward between views, pan, zoom and save a view. \n",
    "\n",
    "A variety of interfaces combining matplotlib display and ipywidgets can be found in the [gui.py](gui.py) file.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ct_image = sitk.ReadImage(fdata('training_001_ct.mha'))\n",
    "ct_window_level = [720,80]\n",
    "mr_window_level = [790,395]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gui.MultiImageDisplay([mr_image, ct_image], figure_size=(10,3), window_level_list=[mr_window_level,ct_window_level]);"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
